package com.wywah.yunduo.security.supports.employee;

import com.wywah.yunduo.security.core.YunduoAuthorizationGrantType;
import com.wywah.yunduo.security.core.YunduoOAuth2ParameterNames;
import com.wywah.yunduo.security.supports.custom.YunduoCustomAuthenticationConverter;
import com.wywah.yunduo.security.utils.OAuth2EndpointUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Set;

/**
 * 用户名密码认证转换器
 */
public class OAuth2EmployeeAuthenticationConverter extends YunduoCustomAuthenticationConverter<OAuth2EmployeeAuthenticationToken>{
    @Override
    public boolean support(String grantType) {
        return YunduoAuthorizationGrantType.EMPLOYEE.getValue().equals(grantType);
    }

    @Override
    public OAuth2EmployeeAuthenticationToken buildToken(Authentication clientPrincipal, Set<String> requestedScopes, Map<String, Object> additionalParameters) {
        return new OAuth2EmployeeAuthenticationToken(YunduoAuthorizationGrantType.PASSWORD, clientPrincipal, requestedScopes, additionalParameters);
    }


    /**
     * 用户名密码不能为空
     * @param request
     */
    @Override
    public void verifyRequest(HttpServletRequest request) {
        MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request);
        String yhdh = parameters.getFirst(YunduoOAuth2ParameterNames.EMPLOYEE);
        if (!StringUtils.hasText(yhdh) || parameters.get(YunduoOAuth2ParameterNames.EMPLOYEE).size() != 1) {
            OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, YunduoOAuth2ParameterNames.EMPLOYEE,
                    OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI);
        }
    }
}